﻿using DevExpress.Blazor;
using DevExpress.ExpressApp.Blazor.Services;
using EasyXaf.LowCode.WorkflowEditors.Models;
using EasyXaf.LowCode.WorkflowEditors.UndoManagers;
using Microsoft.AspNetCore.Components;

namespace EasyXaf.LowCode.WorkflowEditors;

public partial class WorkflowToolbar
{
    [CascadingParameter]
    public IUndoManager UndoManager { get; set; }

    [Parameter]
    public double Zoom { get; set; }

    [Parameter]
    public IContainer Container { get; set; }

    [Parameter]
    public bool PanAndZoomPanelVisible { get; set; }

    [Parameter]
    public EventCallback<double> ZoomChanged { get; set; }

    [Parameter]
    public EventCallback<IContainer> ContainerChanged { get; set; }

    [Parameter]
    public EventCallback BestFit { get; set; }

    [Parameter]
    public EventCallback FitToDrawing { get; set; }

    [Parameter]
    public EventCallback<bool> PanAndZoomPanelVisibleChanged { get; set; }

    [Inject]
    private IImageUrlService ImageUrlService { get; set; }

    private void Undo()
    {
        if (UndoManager.CanUndo)
        {
            UndoManager.Undo();
        }
    }

    private void Redo()
    {
        if (UndoManager.CanRedo)
        {
            UndoManager.Redo();
        }
    }

    private async Task ChangeContainerAsync(IContainer container)
    {
        if (container != Container)
        {
            await ContainerChanged.InvokeAsync(container);
        }
    }

    private IEnumerable<IContainer> GetContainers()
    {
        var containers = new List<IContainer>();
        var container = Container;
        while (container != null)
        {
            containers.Add(container);
            container = container.Container;
        }
        containers.Reverse();
        return containers;
    }

    private async Task ZoomInAsync()
    {
        await ZoomAsync(Zoom + 0.1);
    }

    private async Task ZoomOutAsync()
    {
        await ZoomAsync(Zoom - 0.1);
    }

    private async Task ZoomAsync(double zoom)
    {
        zoom = Math.Min(1.5, zoom);
        zoom = Math.Max(0.1, zoom);
        await ZoomChanged.InvokeAsync(zoom);
    }

    private async Task HandlePanAndZoomPanelVisible(ToolbarItemClickEventArgs e)
    {
        PanAndZoomPanelVisible = !PanAndZoomPanelVisible;
        await PanAndZoomPanelVisibleChanged.InvokeAsync(PanAndZoomPanelVisible);
    }

    public async Task RaiseZoomChangedAsync(double zoom)
    {
        Zoom = zoom;
        await InvokeAsync(StateHasChanged);
    }
}
